<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="材料名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入材料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库存数量" prop="total">
        <el-input
          v-model="queryParams.total"
          placeholder="请输入库存数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材料单价" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入材料单价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材料总价" prop="totalPrice">
        <el-input
          v-model="queryParams.totalPrice"
          placeholder="请输入材料总价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ycl:material:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ycl:material:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ycl:material:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ycl:material:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="材料ID" align="center" prop="materialId" />
      <el-table-column label="材料名称" align="center" prop="name" />
      <el-table-column label="材料描述" align="center" prop="description" width="200"/>
      <el-table-column label="图片" align="center">
        <template slot-scope="scope">
          <img
            v-if="scope.row.picture"
            :src="scope.row.picture"
            alt="图片预览"
            style="width: 50px; height: 50px; cursor: pointer; border: 2px solid transparent; transition: border-color 0.3s;"
            @click="showLargeImage(scope.row.picture)"
            @mouseover="hoverImage(true)"
            @mouseout="hoverImage(false)"
          />
        </template>
      </el-table-column>
      <el-table-column label="库存数量" align="center" prop="total" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="材料单价" align="center" prop="price" />
      <el-table-column label="材料总价" align="center" prop="totalPrice" />
      <el-table-column label="更新时间" align="center" prop="updateAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ycl:material:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ycl:material:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改材料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="材料名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入材料名称" />
        </el-form-item>
        <el-form-item label="材料描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="数量" prop="total">
          <el-input v-model="form.total" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="材料单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入材料价格" />
        </el-form-item>
        <el-form-item label="图片" prop="picture" v-show="false">
          <el-input v-model="form.picture" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-image
          style="width: 300px; height: 300px"
          :src="url"
          :fit="fit" ref="imageId" >
        </el-image>
        <el-upload
          ref="uploadFile"
          :limit="1"
          accept=".bmp,.jpg,.jpeg,.png,gif"
          :headers="uploadData.headers"
          :action="uploadData.url"
          :disabled="uploadData.isUploading"
          :on-progress="handleFileUploadDataProgress"
          :on-success="handleFileDataSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <span>仅允许导入bmp、jpg、jpeg、gif、png格式文件。</span>
        </el-upload>
        <el-button type="primary" @click="submitFileFormImage">上传图片</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 显示大图的模态框 -->
    <el-dialog :visible.sync="dialogVisible" width="50%">
      <img :src="largeImageUrl" alt="大图预览" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial } from "@/api/ycl/material";
import { getToken } from "@/utils/auth";

export default {
  name: "Material",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 图片导入参数
      uploadData: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ycl/material/uploadMinio"
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        description: null,
        total: null,
        createdAt: null,
        price: null,
        totalPrice: null,
        updateAt: null,
        picture: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

      url: '', // 初始图片URL  
      fit: 'contain', // 图片适应方式，这里设置为'contain'

      dialogVisible: false,
      largeImageUrl: '',
      borderColor: 'transparent'      
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询材料列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;

        this.form.picture = this.url;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: null,
        name: null,
        description: null,
        total: null,
        createdAt: null,
        price: null,
        totalPrice: null,
        updateAt: null,
        picture: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      console.log(this.queryParams);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加材料";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materialId = row.materialId || this.ids;
      getMaterial(materialId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改材料";

        this.url = this.form.picture;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.materialId != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialIds = row.materialId || this.ids;
      this.$modal.confirm('是否确认删除材料编号为"' + materialIds + '"的数据项？').then(function () {
        return delMaterial(materialIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ycl/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    },

    // 图片文件上传中处理
    handleFileUploadDataProgress(event, file, fileList) {
      this.uploadData.isUploading = true;
    },

  /** 图片文件上传成功处理 */
  handleFileDataSuccess(response, file, fileList) {
    this.uploadData.isUploading = false;
    this.$refs.uploadFile.clearFiles();

    this.form.picture = response.msg;
    this.url = this.form.picture;

    this.$alert("<div style='overflow: auto; overflow-x: hidden; max-height: 70vh; padding: 10px 20px 0;'>上传图片成功！</div>", "导入结果", { dangerouslyUseHTMLString: true });
  },

  // 提交上传文件
  submitFileFormImage() {
    this.$refs.uploadFile.submit();
  },

  // 显示大图
  showLargeImage(url) {
    this.largeImageUrl = url;
    this.dialogVisible = true;
  },

  // 鼠标悬停效果
    hoverImage(isHovering) {
      this.borderColor = isHovering ? '#409EFF' : 'transparent';
    },

  // 图片下载
  handleDownImage(filename) {
    let pos = filename.lastIndexOf("/");
    filename = filename.substring(pos);
    let extendName = filename.substring(filename.indexOf("."));
    this.download('ycl/material/imageDown', { fileName: filename }, `student_image_${new Date().getTime()}` + extendName);
  }
}
};
</script>